<template>
  <view class="face-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="platform-name">xx平台</text>
      <view class="header-actions">
        <!-- <image src="@/static/images/icon/info.png" class="header-icon" /> -->
        <!-- <image src="@/static/images/icon/settings.png" class="header-icon" /> -->
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <view class="banner-timer">
        <text class="timer-text">#2020全高告白日#</text>
      </view>
      <swiper
        :autoplay="autoplay"
        :indicator-color="indicatorColor"
        :interval="interval"
        :duration="duration"
        :indicator-active-color="indicatorActiveColor + ' '"
        :circular="true"
        class="pic-swiper"
        indicator-dots
        previous-margin="20rpx"
        next-margin="20rpx"
      >
        <block v-for="(item, index) in indexImgs" :key="index">
          <swiper-item class="banner-item">
            <view class="img-box">
              <image
                :src="item.imgUrl"
                :data-prodid="item.relation"
                class="banner"
                @tap="toProdPage"
              />
            </view>
          </swiper-item>
        </block>
      </swiper>
    </view>

    <!-- 欢迎语 -->
    <view class="welcome-section">
      <text class="welcome-title">AI欢迎来到xx平台</text>
      <text class="welcome-subtitle">创作属于您的玩偶</text>
    </view>

    <!-- 选择玩场 -->
    <view class="playground-section">
      <text class="section-title">选择玩场</text>

      <!-- 性别切换按钮 -->
      <view class="face-type-switcher">
        <view
          class="type-btn"
          :class="{ active: currentFaceType === 1 }"
          @tap="switchFaceType(1)"
        >
          男性
        </view>
        <view
          class="type-btn"
          :class="{ active: currentFaceType === 2 }"
          @tap="switchFaceType(2)"
        >
          女性
        </view>
        <view
          class="type-btn"
          :class="{ active: currentFaceType === 3 }"
          @tap="switchFaceType(3)"
        >
          通用
        </view>
      </view>

      <view class="avatar-grid">
        <view
          v-for="(avatar, index) in avatars"
          :key="avatar.id || index"
          class="avatar-item"
          :class="{ active: selectedAvatarId === (avatar.faceBaseId || avatar.id) }"
          @tap="selectAvatar(avatar)"
        >
          <view v-if="avatar.faceImageUrl" class="avatar-circle">
            <image :src="avatar.faceImageUrl" class="avatar-img" mode="aspectFill" />
          </view>
          <text class="avatar-label">{{ avatar.faceName }}</text>
          <view v-if="selectedAvatarId === (avatar.faceBaseId || avatar.id)" class="selected-mark">
            <text class="selected-icon">✓</text>
          </view>
        </view>
      </view>

      <!-- 开始定制按钮 -->
      <view class="start-customize-btn" @tap="startCustomize" :class="{ disabled: !selectedAvatarId }">
        <text class="start-customize-text">{{ selectedAvatarId ? '开始定制' : '请先选择头像' }}</text>
      </view>

      <!-- 加载更多按钮 -->
      <view v-if="currentPage < totalPages" class="load-more">
        <text class="load-more-text" @tap="loadMoreAvatars">加载更多</text>
      </view>

      <!-- 刷新按钮 -->
      <view class="refresh-btn">
        <text class="refresh-text" @tap="refreshAvatars">刷新头像</text>
      </view>
    </view>
  </view>
  <custom-tabbar :currentTab="currentTab" @tabChange="handleTabChange" />
</template>

<script setup>
import { ref } from "vue";
import CustomTabbar from "@/components/custom-tabbar/index.vue";
import http from "@/utils/http.js";

// 需要在return中暴露的变量
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL;

// tab状态管理
const currentTab = ref("index");

// 处理tab切换
const handleTabChange = (tab) => {
  currentTab.value = tab;
};

// 轮播图设置
const indicatorColor = ref('#d1e5fb')
const indicatorActiveColor = ref('#1b7dec')
const autoplay = ref(true);
const interval = ref(3000);
const duration = ref(1000);
const indexImgs = ref([]);
const seq = ref(0);




// 头像数据
const avatars = ref([]);
const currentFaceType = ref(1); // 1:男性, 2:女性, 3:通用
const currentPage = ref(1);
const pageSize = ref(12);
const totalPages = ref(1);
const selectedAvatarId = ref(null); // 存储选中的头像ID

// 页面加载时设置当前tab
onLoad(() => {
  currentTab.value = "index";
  getAllData();
  loadFaceBases();
});
onShow(() => {
  uni.hideTabBar();
});

// 选择头像
const selectAvatar = (avatar) => {
  selectedAvatarId.value = avatar.faceBaseId || avatar.id;
  console.log('选择了头像:', selectedAvatarId.value)
  // 这里可以添加头像选择后的逻辑，比如跳转到定制页面
}

// 获取人脸底图列表
const loadFaceBases = async () => {
  try {
    const response = await http.request({
      url: '/faceBase/page',
      method: 'GET',
      data: {
        page: currentPage.value,
        limit: pageSize.value,
        faceType: currentFaceType.value,
        status: 1 // 只获取启用的底图
      },
      header: {
        'Content-Type': 'application/json',
        // 'Authorization': '80e46f24-cdf5-4cac-bb7e-2f7fd0f4d71b' // 如果需要认证
      }
    });

    if (response.data) {
      console.log('获取人脸底图成功:', response.data);

      // 转换接口数据格式
      response.data.records.forEach((item, index) => {
        item.faceImageUrl = resourcesUrl + item.faceImageUrl;
      });
      avatars.value = response.data.records;

      totalPages.value = Math.ceil(response.data.total / pageSize.value);
    }
  } catch (error) {
    console.error('获取人脸底图失败:', error);
    // 如果接口失败，使用默认数据
    loadDefaultAvatars();
  }
}

// 加载默认头像数据
const loadDefaultAvatars = () => {
  avatars.value = [
    { label: "A", image: "", id: 1, faceType: currentFaceType.value, name: "默认头像A" },
    { label: "B", image: "", id: 2, faceType: currentFaceType.value, name: "默认头像B" },
    { label: "C", image: "", id: 3, faceType: currentFaceType.value, name: "默认头像C" },
    { label: "D", image: "", id: 4, faceType: currentFaceType.value, name: "默认头像D" },
    { label: "E", image: "", id: 5, faceType: currentFaceType.value, name: "默认头像E" },
    { label: "F", image: "", id: 6, faceType: currentFaceType.value, name: "默认头像F" },
    { label: "G", image: "", id: 7, faceType: currentFaceType.value, name: "默认头像G" },
    { label: "H", image: "", id: 8, faceType: currentFaceType.value, name: "默认头像H" },
    { label: "I", image: "", id: 9, faceType: currentFaceType.value, name: "默认头像I" },
    { label: "J", image: "", id: 10, faceType: currentFaceType.value, name: "默认头像J" },
    { label: "K", image: "", id: 11, faceType: currentFaceType.value, name: "默认头像K" },
    { label: "L", image: "", id: 12, faceType: currentFaceType.value, name: "默认头像L" }
  ];
};

// 切换性别
const switchFaceType = (type) => {
  currentFaceType.value = type;
  currentPage.value = 1;
  loadFaceBases();
};

// 加载更多头像
const loadMoreAvatars = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    loadFaceBases();
  }
};

// 开始定制
const startCustomize = () => {
  if (!selectedAvatarId.value) {
    uni.showToast({
      title: '请先选择头像',
      icon: 'none'
    });
    return;
  }
  console.log("开始定制，选中的头像ID:", selectedAvatarId.value);
  // 跳转到定制页面并传递选中的头像ID
  uni.navigateTo({
    url: `/pages/customize/customize?avatarId=${selectedAvatarId.value}`,
  });
};

// 刷新头像数据
const refreshAvatars = () => {
  currentPage.value = 1;
  loadFaceBases();
};

const getAllData = () => {
  getIndexImgs();
};

/**
 * 加载轮播图
 */
const getIndexImgs = () => {
  http
    .request({
      url: "/indexImgs",
      method: "GET",
      data: {},
    })
    .then(({ data }) => {
      indexImgs.value = data;
      seq.value = data;
    });
};

const toProdPage = (e) => {
  const prodid = e.currentTarget.dataset.prodid;

  if (prodid) {
    uni.navigateTo({
      url: "/pages/prod/prod?prodid=" + prodid,
    });
  }
};
</script>

<style scoped lang="scss">
@use "./index.scss";
/* 为自定义tabBar留出空间 */
.face-container {
  padding-bottom: 120rpx;
}

/* 开始定制按钮样式 */
.start-customize-btn {
  margin: 40rpx auto;
  width: 60%;
  height: 80rpx;
  background-color: #1b7dec;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s;

  &:active {
    background-color: #0e5aa7;
  }

  &.disabled {
    background-color: #ccc;

    &:active {
      background-color: #ccc;
    }
  }

  .start-customize-text {
    color: white;
    font-size: 32rpx;
    font-weight: bold;
  }
}
</style>
